<template>
  <div class="form-detail-page">
    <div class="form-add-content" :class="hasActions">
      <div class="form-card van-hairline--top-bottom" v-for="(item, index) in runjs" :key="index">
        <component 
          :is="'mb-' + item.type" 
          :options="item"
          :flowConfig="flowConfig"
          :ref="item.key"
          :readonly = "toolbar.type ==='query'"
          v-if="item.type !== 'flow-chart'"
          @formdataChange="formdataChange"
          @subgridChange="subgridChange"
        ></component>
      </div>
      <mb-flow-next-step
        ref="nextStep"
        :taskId="flowConfig.taskId" 
        :defId="flowConfig.defId"
        :defKey="flowConfig.defKey"
        :multiple="!flowConfig.singleSelectAssignees"
        :defaultCustom="!flowConfig.cannotSelectInAll"
        v-if="canRender && (flowConfig.needSelectNode || flowConfig.showNextAssignees)">
      </mb-flow-next-step>
    </div>
    <van-row class="form-actions">
      <van-col :span="btnList.length<2?24:12" v-for="(btn,index) in btnList" :key="index">
        <van-button 
          :type="btnList.length === 2?(index?'info':'default'):'info'"
          block 
          @click="btnClick(btn, index)"
        >
          {{btn.name}}
        </van-button>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import { request } from 'utils/http'
import { recalculate } from 'utils'
import MbRawHtml from '../controls/raw-html'
import MbSubGrid from '../controls/sub-grid'
import MbSubForm from '../controls/sub-form'
import MbSectionTitle from '../controls/section-title'
import MbFlowStatus from '../controls/flow-status'
import MbAuditComment from '../controls/audit-comment'
import MbFlowNextStep from '../controls/emap-flow-next-step'
import ToolbarMixin from 'utils/mixinToolbar'


export default {
  name: 'mb-form-operation',
  components: {
    MbRawHtml, MbSubGrid, MbSubForm, MbSectionTitle, MbFlowStatus, MbAuditComment, MbFlowNextStep
  },
  data () {
    return {
      toolbar: {},
      item: {},
      runjs: [],
      meta: [],
      defaultValue: {},
      flowConfig: {},
      btnList: [],
      canRender: false,
      WID: null
    }
  },
  mixins: [ToolbarMixin],
  computed: {
    hasActions() {
      return this.btnList.length > 0 ? 'hasActions' : ''
    }
  },
  methods: {
    init() {
      if(!this.$route.params.toolbar) {
        history.back();
        return
      }
      const _this = this;
      this.toolbar = this.$route.params.toolbar;
      let uploadUrlPre = this.toolbar.formUrl.slice(0, this.toolbar.formUrl.indexOf("showForm.do"));
      this.item = this.$route.params.item;
      let propParam = {};
      if(this.toolbar.params) {
        this.toolbar.params.forEach( param => {
          propParam[param.name] = param.value;
        })
      }
      let key = {
        "time": this.item.time,
        "bizKey": this.item.$$bizKey,
        "sign": this.item.$$sign
      };
      request(this.toolbar.formUrl, {
          query: {
            alias: this.toolbar.form,
            gridAlias: this.toolbar.gridAlias,
            key: JSON.stringify(key),
            ...propParam
          },
        }).then(res => {
          if(res.code !== "0") {
            this.$notify({ type: 'danger', message: '获取表单信息失败' });
            return
          }

          // 赋值
          const dataModels = res.models;
          const datas = res.datas;
          _this.runjs = dataModels.runjs && JSON.parse(dataModels.runjs).children;
          _this.meta = dataModels.meta;
          _this.defaultValue = datas.result;
          _this.canRender = true;
          _this.flowConfig = datas.flowConfig;
          _this.flowConfig.needFlowOpt = datas.needFlowOpt;
          _this.flowConfig.___procStatus = _this.item.___procStatus;
          _this.flowConfig.___procStatus_DISPLAY = _this.item.___procStatus_DISPLAY;
          _this.WID = datas.key.bizKey;

          // 过滤类型为 "flow-chart"、“flow-status”的子项
          let filterArr = ["audit-comment", "flow-status", "raw-html", "section-title", "sub-form", "sub-grid"];
          _this.runjs = _this.runjs.filter( item => {
            if(_this.toolbar.type === 'query') {
              return filterArr.indexOf(item.type) >0
            } else {
              return filterArr.indexOf(item.type) >-1
            }
          });

          // 针对 [sub-grid] [sub-form] 将meta，supportSigns以及time整合入runjs，
          // 针对 [flow-status] 将flowConfig整合进去
          if(_this.runjs.length) {
            let hashMeta = new Array();
            _this.meta.forEach( meta => {
              if(meta.dataType === 'Clob') {
                meta.uploadUrlPre = uploadUrlPre;
                meta.key = datas.key
              }
              hashMeta[meta.name] = meta;
            });
            _this.runjs = _this.runjs.map( item => {
              if(item.type === "sub-grid") {
                item["meta"] = hashMeta[item.options.tableName]
              } else if (item.type === "sub-form") {
                item["meta"] = [];
                item.options.models.forEach( model => {
                  item["meta"].push(hashMeta[model])
                })
              } else if (item.type === "flow-status") {
                item.flowConfig = _this.flowConfig
              }
              item.supportSigns = dataModels.supportSigns;
              item.time = dataModels.time;
              item.defaultValue = datas.result;
              return item
            });
          }
          // 获取toolbar
          _this.getToolbar();
        });
    },
    getToolbar() {
      const _this = this;
      let query = {};
      let url = "";
      let exclude_type = "";
      if (!this.flowConfig.taskId && this.flowConfig.defKey ) {
        exclude_type = "submit";
        query.defKey = this.flowConfig.defKey;
        url = "/sys/emapflow/definition/queryFirstUserTaskToolbar.do";
      } else if (this.flowConfig.taskId) {
        exclude_type = "start";
        query.taskId = this.flowConfig.taskId;
        url = "/sys/emapflow/definition/queryUserTaskToolbar.do";
      } else {
        throw new Error("toolbar渲染，参数不满足，taskId or defKey 都没有");
      }
      // 移动1.0按照王志伟所说，暂时只支持 “启动”，“保存草稿”，“终止”，“追回”，“退回操作”；
      let validBtn = ["start", "draft", "submit", "termination", "turnback", "callback"];
      request( url, {
        query: query
      }).then(res => {
        let btns = res.commands;
        // 特别说明：按钮显示抛去 processStatus 的类型(该类型已在页头固定显示)，余下的选择前两个展示 （核对人：王志伟 2020/1/21）
        // 发起、查看、编辑页面该处保持一致
        _this.btnList = btns.filter( btn => {
          return btn.commandType !== exclude_type && validBtn.indexOf(btn.commandType)>-1
        })
        if(_this.btnList.length>2) {
          _this.btnList = _this.btnList.slice(0,2);
        }
      })
    },
    formdataChange(name, values, item) {
      if(item.nextNode && item.nextNode === "true" && this.$refs.nextStep) {
        this.$refs.nextStep.updateNextNodes();
      }
      // 针对审核意见特殊处理
      if(item.type && item.type === "audit-comment" && this.$refs.nextStep) {
        this.$refs.nextStep.updateNextNodes();
      }
    },
    subgridChange(name, values, meta) {
      // 主表关联子表计算属性处理
      const _this = this;
      this.runjs.forEach( item => {
        if(item.type == 'sub-form') {
          let subformVm =_this.$refs[item.key][0];
          let filterMeta = subformVm.meta.filter(opt => {
            return opt.computeRule && opt.computeRule.indexOf(name) > -1
          })
          if(filterMeta.length) {
            let metas  = [meta].concat(subformVm.meta)
            let newData = recalculate(_this.getFormData(), metas);
            metas.forEach(opt => {
              if(newData[opt.name] && subformVm.vm.$refs[opt.name]){
                subformVm.vm.$refs[opt.name].value = newData[opt.name]
              }
            })
          }
        }
      })
    },
    btnClick(btn, idx) {
      // 获取formdata
      if(this.toolbar.type === 'query') {
        this.formData = this.defaultValue
      }else{
        if(!this.validate()) return
        this.formData = this.getFormData(btn)
      }
      // 继承流程所需
      if(this.WID) this.formData.WID = this.WID;

      // 获取【意见审批】并校验，注：除【启动】外，即taskId都存在的情况下，无论是否存在审批意见，comment.flowComment字段都应该存在， 核对人：王志伟2020/02/18
      let comment = {flowComment: ''};

      let auditComment = this.runjs.filter( item => {
        return item.type == 'audit-comment'
      });
      if(auditComment && auditComment.length) {
        const commentVM = this.$refs[auditComment[0].key][0];
        if(!commentVM.validate()) return
        if(commentVM.commentObj.approval_display && commentVM.commentObj.comment) {
          comment.flowComment = commentVM.commentObj.approval_display + ',' + commentVM.commentObj.comment
        }else{
          comment.flowComment = commentVM.commentObj.approval_display || commentVM.commentObj.comment
        }
      }
      
      // 获取【下一步组件】值并校验
      let nextStep = {};
      if(this.flowConfig.needSelectNode || this.flowConfig.showNextAssignees) {
        const nextstepVM = this.$refs.nextStep;
        if(!nextstepVM.isFinishedTask) {
          nextStep = nextstepVM.nextstepObj;
          if (btn.id === 'start' || btn.id === 'submit') {
            if(!nextstepVM.validate())  return
          }
        }
      }

      let query = Object.assign(
        {}, 
        btn,
        comment,
        nextStep,
        {
          alias: this.toolbar.form,
          gridAlias: this.toolbar.gridAlias,
          taskId: this.flowConfig.taskId || '',
          defKey: this.flowConfig.defKey || '',
          formData: JSON.stringify(this.formData)
        }
      );

      // 限流
      btn.disabled = true;
      this.$set(this.btnList, idx, btn);
      
      this[btn.execute](btn, query).then( res =>{
        if(res.succeed) {
          this.$notify({ type: 'success', message: btn.name + '成功' });
          setTimeout(() => {
            history.back();
          },1000)
        }
      })
    },
    validate() {
      let valid = true;
      const _this = this;
      this.runjs.forEach( item => {
        if(item.type == 'sub-form') {
          if(!_this.$refs[item.key][0].validate()) valid = false;
        }
      })
      return valid
    },
    getFormData() {
      const _this = this;
      let formData = {};
      this.runjs.forEach( item => {
        if(item.type == 'sub-form') {
          formData = Object.assign(formData, _this.$refs[item.key][0].formData);
        } else if(item.type == 'sub-grid') {
          let subGridVM = _this.$refs[item.key][0];
          formData[subGridVM.subGridTitle] = _this.$refs[item.key][0].subGridList
        } else if(item.type == 'audit-comment') {
          const commentVM = _this.$refs[item.key][0];
          if(commentVM.chapterWID) formData.elecseal = commentVM.chapterWID;
          if(commentVM.commentObj.approval) formData["approval"] = commentVM.commentObj.approval_display;
        }
      })
      // 对于以"___"开头的变量进行反转化
      for(var key in formData) {
        if(/N___/.test(key)){
          formData[key.slice(1)] = formData[key];
          delete formData[key];
        }
      }
      return formData
    }
  },
  mounted() {
    this.init();
  },
}
</script>
<style>
.form-detail-page {
  background-color: #F9F9F9;
  height: 100vh;
  overflow: auto;
  position: relative;
}
.form-actions {
  position: absolute;
  bottom: 0;
  width: 100%;
}
.cell-group-readonly .van-cell__title {
  color: #969799;
}
</style>